// components/classic/music/index.js
import {
  classicBehavior
} from "../classic-behavior.js";

let mMgr = wx.getBackgroundAudioManager();
Component({
  /**
   * 引入的behavior
   */
  behaviors: [classicBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    src: String,
    title: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    playing: false,
    pauseSrc: "../../images/player@waitting.png",
    playSrc: "../../images/player@playing.png",
  },

  attached: function () {
    this._recoverMusicStatus();
    this._monitorSwitch();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onPlay: function () {
      if (!this.data.playing) {
        this.setData({
          playing: true
        });
        mMgr.src = this.properties.src;
        mMgr.title = this.properties.title;
      } else {
        this.setData({
          playing: false
        });
        mMgr.pause();
      }
    },
    /**
     * 恢复音乐播放器状态
     */
    _recoverMusicStatus: function () {
      if (mMgr.paused) {
        this.setData({
          playing: false,
        });
      } else if (mMgr.src == this.properties.src) {
        this.setData({
          playing: true,
        });
      }
    },
    /**
     * 监听音乐播放器的中断事件
     */
    _monitorSwitch: function () {
      mMgr.onPlay(() => {
        this._recoverMusicStatus();
      });
      mMgr.onPause(() => {
        this._recoverMusicStatus();
      });
      mMgr.onStop(() => {
        this._recoverMusicStatus();
      });
      mMgr.onEnded(() => {
        this._recoverMusicStatus();
      });
    }
  }


})